<% layout('/layouts/default.html', {title: 'Blockly项目设计', libs: []}){ %>
<div class="content">
	<xml xmlns="https://developers.google.com/blockly/xml" id="toolbox" style="display: none;">
		<category name="Logic" colour="%{BKY_LOGIC_HUE}">
			<category name="If">
				<block type="controls_if"></block>
				<block type="controls_if">
					<mutation else="1"></mutation>
				</block>
				<block type="controls_if">
					<mutation elseif="1" else="1"></mutation>
				</block>
			</category>
			<category name="Boolean">
				<block type="logic_compare"></block>
				<block type="logic_operation"></block>
				<block type="logic_negate"></block>
				<block type="logic_boolean"></block>
				<block type="logic_null"></block>
				<block type="logic_ternary"></block>
			</category>
		</category>
		<category name="Loops" colour="%{BKY_LOOPS_HUE}">
			<block type="controls_repeat_ext">
				<value name="TIMES">
					<block type="math_number">
						<field name="NUM">10</field>
					</block>
				</value>
			</block>
			<block type="controls_whileUntil"></block>
			<block type="controls_for">
				<field name="VAR">i</field>
				<value name="FROM">
					<block type="math_number">
						<field name="NUM">1</field>
					</block>
				</value>
				<value name="TO">
					<block type="math_number">
						<field name="NUM">10</field>
					</block>
				</value>
				<value name="BY">
					<block type="math_number">
						<field name="NUM">1</field>
					</block>
				</value>
			</block>
			<block type="controls_forEach"></block>
			<block type="controls_flow_statements"></block>
		</category>
		<category name="Math" colour="%{BKY_MATH_HUE}">
			<block type="math_number">
				<field name="NUM">123</field>
			</block>
			<block type="math_arithmetic"></block>
			<block type="math_single"></block>
			<block type="math_trig"></block>
			<block type="math_constant"></block>
			<block type="math_number_property"></block>
			<block type="math_round"></block>
			<block type="math_on_list"></block>
			<block type="math_modulo"></block>
			<block type="math_constrain">
				<value name="LOW">
					<block type="math_number">
						<field name="NUM">1</field>
					</block>
				</value>
				<value name="HIGH">
					<block type="math_number">
						<field name="NUM">100</field>
					</block>
				</value>
			</block>
			<block type="math_random_int">
				<value name="FROM">
					<block type="math_number">
						<field name="NUM">1</field>
					</block>
				</value>
				<value name="TO">
					<block type="math_number">
						<field name="NUM">100</field>
					</block>
				</value>
			</block>
			<block type="math_random_float"></block>
			<block type="math_atan2"></block>
		</category>
		<category name="文本" colour="%{BKY_TEXTS_HUE}">
			<block type="text"></block>
			<block type="text_multiline"></block>
			<block type="text_join"></block>
			<block type="text_create_join_container"></block>
			<block type="text_create_join_item"></block>
			<block type="text_append"></block>
			<block type="text_length"></block>
			<block type="text_isEmpty"></block>
			<block type="text_indexOf"></block>
			<block type="text_charAt"></block>
			<block type="text_getSubstring"></block>
			<block type="text_changeCase"></block>
			<block type="text_trim"></block>
			<block type="text_print"></block>
			<block type="text_prompt_ext"></block>
			<block type="text_prompt"></block>
			<block type="text_count"></block>
			<block type="text_replace"></block>
			<block type="text_reverse"></block>
		</category>
		<category name="列表" colour="%{BKY_LISTS_HUE}">
			<block type="lists_create_empty"></block>
			<block type="lists_create_with"></block>
			<block type="lists_repeat">
				<value name="NUM">
					<block type="math_number">
						<field name="NUM">5</field>
					</block>
				</value>
			</block>
			<block type="lists_length"></block>
			<block type="lists_isEmpty"></block>
			<block type="lists_indexOf"></block>
			<block type="lists_getIndex"></block>
			<block type="lists_setIndex"></block>
		</category>
		<sep></sep>
		<category name="变量" custom="VARIABLE" colour="%{BKY_VARIABLES_HUE}"></category>
		<category name="函数" custom="PROCEDURE" colour="%{BKY_PROCEDURES_HUE}"></category>
		<category name="回调函数" custom="Category_Callbacks" colour="%{BKY_CALLBACK_HUE}"></category>
		<sep></sep>
		<category name="库">
			<category name="Randomize">
				<block type="procedures_defnoreturn">
					<mutation>
						<arg name="list"></arg>
					</mutation>
					<field name="NAME">randomize</field>
					<statement name="STACK">
						<block type="controls_for" inline="true">
							<field name="VAR">x</field>
							<value name="FROM">
								<block type="math_number">
									<field name="NUM">1</field>
								</block>
							</value>
							<value name="TO">
								<block type="lists_length" inline="false">
									<value name="VALUE">
										<block type="variables_get">
											<field name="VAR">list</field>
										</block>
									</value>
								</block>
							</value>
							<value name="BY">
								<block type="math_number">
									<field name="NUM">1</field>
								</block>
							</value>
							<statement name="DO">
								<block type="variables_set" inline="false">
									<field name="VAR">y</field>
									<value name="VALUE">
										<block type="math_random_int" inline="true">
											<value name="FROM">
												<block type="math_number">
													<field name="NUM">1</field>
												</block>
											</value>
											<value name="TO">
												<block type="lists_length" inline="false">
													<value name="VALUE">
														<block type="variables_get">
															<field name="VAR">list</field>
														</block>
													</value>
												</block>
											</value>
										</block>
									</value>
									<next>
										<block type="variables_set" inline="false">
											<field name="VAR">temp</field>
											<value name="VALUE">
												<block type="lists_getIndex" inline="true">
													<mutation statement="false" at="true"></mutation>
													<field name="MODE">GET</field>
													<field name="WHERE">FROM_START</field>
													<value name="AT">
														<block type="variables_get">
															<field name="VAR">y</field>
														</block>
													</value>
													<value name="VALUE">
														<block type="variables_get">
															<field name="VAR">list</field>
														</block>
													</value>
												</block>
											</value>
											<next>
												<block type="lists_setIndex" inline="false">
													<value name="AT">
														<block type="variables_get">
															<field name="VAR">y</field>
														</block>
													</value>
													<value name="LIST">
														<block type="variables_get">
															<field name="VAR">list</field>
														</block>
													</value>
													<value name="TO">
														<block type="lists_getIndex" inline="true">
															<mutation statement="false" at="true"></mutation>
															<field name="MODE">GET</field>
															<field name="WHERE">FROM_START</field>
															<value name="AT">
																<block type="variables_get">
																	<field name="VAR">x</field>
																</block>
															</value>
															<value name="VALUE">
																<block type="variables_get">
																	<field name="VAR">list</field>
																</block>
															</value>
														</block>
													</value>
													<next>
														<block type="lists_setIndex" inline="false">
															<value name="AT">
																<block type="variables_get">
																	<field name="VAR">x</field>
																</block>
															</value>
															<value name="LIST">
																<block type="variables_get">
																	<field name="VAR">list</field>
																</block>
															</value>
															<value name="TO">
																<block type="variables_get">
																	<field name="VAR">temp</field>
																</block>
															</value>
														</block>
													</next>
												</block>
											</next>
										</block>
									</next>
								</block>
							</statement>
						</block>
					</statement>
				</block>
			</category>
			<category name="Jabberwocky">
				<block type="text_print">
					<value name="TEXT">
						<block type="text">
							<field name="TEXT">'Twas brillig, and the slithy toves</field>
						</block>
					</value>
					<next>
						<block type="text_print">
							<value name="TEXT">
								<block type="text">
									<field name="TEXT">  Did gyre and gimble in the wabe:</field>
								</block>
							</value>
							<next>
								<block type="text_print">
									<value name="TEXT">
										<block type="text">
											<field name="TEXT">All mimsy were the borogroves,</field>
										</block>
									</value>
									<next>
										<block type="text_print">
											<value name="TEXT">
												<block type="text">
													<field name="TEXT">  And the mome raths outgrabe.</field>
												</block>
											</value>
										</block>
									</next>
								</block>
							</next>
						</block>
					</next>
				</block>
				<block type="text_print">
					<value name="TEXT">
						<block type="text">
							<field name="TEXT">"Beware the Jabberwock, my son!</field>
						</block>
					</value>
					<next>
						<block type="text_print">
							<value name="TEXT">
								<block type="text">
									<field name="TEXT">  The jaws that bite, the claws that catch!</field>
								</block>
							</value>
							<next>
								<block type="text_print">
									<value name="TEXT">
										<block type="text">
											<field name="TEXT">Beware the Jubjub bird, and shun</field>
										</block>
									</value>
									<next>
										<block type="text_print">
											<value name="TEXT">
												<block type="text">
													<field name="TEXT">  The frumious Bandersnatch!"</field>
												</block>
											</value>
										</block>
									</next>
								</block>
							</next>
						</block>
					</next>
				</block>
			</category>
		</category>
		<sep></sep>
		<category name="时间" colour="%{BKY_TIME_HUE}">
			<block type="time_package"></block>
			<block type="time_sleep"></block>
		</category>
		<category name="树莓派" colour="%{BKY_RASPBERRY_PINIO_HUE}">
			<block type="pinio_package"></block>
			<block type="pinio_mode"></block>
			<block type="pinio_get_mode"></block>
			<block type="pinio_set_mode"></block>
			<block type="pinio_pin_mode"></block>
			<block type="pinio_set_pin_mode"></block>
			<block type="pinio_pin_level"></block>
			<block type="pinio_set_pin_level"></block>
			<block type="pinio_get_pin_level"></block>
			<block type="pinio_pin_event"></block>
			<block type="pinio_add_event_detect"></block>
			<block type="pinio_remove_event_detect"></block>
			<block type="pinio_cleanup"></block>
		</category>
		<category name="MQTT服务" colour="%{BKY_PAHO_MQTT_HUE}">
			<block type="paho_mqtt_package"></block>
			<block type="paho_mqtt_init">
				<value name="CLIENT">
					<block type="logic_null"></block>
				</value>
				<value name="SESSION">
					<block type="logic_boolean">
						<field name="BOOL">TRUE</field>
					</block>
				</value>
			</block>
			<block type="paho_mqtt_username_password">
				<value name="USERNAME">
					<block type="text">
						<field name="TEXT">mybroker</field>
					</block>
				</value>
				<value name="PASSWORD">
					<block type="text">
						<field name="TEXT">mybroker</field>
					</block>
				</value>
			</block>
			<block type="paho_mqtt_on_connect"></block>
			<block type="paho_mqtt_qos"></block>
			<block type="paho_mqtt_subscribe"></block>
			<block type="paho_mqtt_publish"></block>
			<block type="paho_mqtt_on_message"></block>
			<block type="paho_mqtt_message_topic"></block>
			<block type="paho_mqtt_message_payload"></block>
			<block type="paho_mqtt_message_qos"></block>
			<block type="paho_mqtt_connect">
				<value name="SERVER">
					<block type="text">
						<field name="TEXT">116.63.150.120</field>
					</block>
				</value>
				<value name="PORT">
					<block type="math_number">
						<field name="NUM">1883</field>
					</block>
				</value>
				<value name="KEEP_ALIVE">
					<block type="math_number">
						<field name="NUM">60</field>
					</block>
				</value>
			</block>
			<block type="paho_mqtt_disconnect"></block>
			<block type="paho_mqtt_loop_stop"></block>
		</category>
		<category name="JSON" colour="%{BKY_DEMJSON_HUE}">
			<block type="demjson_package"></block>
			<block type="demjson_create"></block>
			<block type="demjson_decode"></block>
			<block type="demjson_encode"></block>
			<block type="demjson_get"></block>
			<block type="demjson_set"></block>
		</category>
		<category name="华为IoT" colour="%{BKY_HW_IOT_HUE}">
			<block type="hw_iot_package"></block>
			<block type="hw_iot_server_url"></block>
			<block type="hw_iot_client_id"></block>
			<block type="hw_iot_encrypt_password"></block>
			<block type="hw_iot_device_commad_topic"></block>
			<block type="hw_iot_device_report_topic"></block>
			<block type="hw_iot_device_report_service"></block>

		</category>
	</xml>

	<div id="headDiv">
		&nbsp;
		<button id="save" class="btn btn-success" href="javascript:void(0);" title="保存设计"><i class="fa fa-save"></i> 保存设计</button>&nbsp;&nbsp;
		<button id="generate_code_button" class="btn btn-success" href="javascript:void(0);" title="生成Python代码"><i class="fa fa-code"></i> 生成代码</button>&nbsp;&nbsp;
		<button id="download_code" class="btn btn-success" href="javascript:void(0);" title="下载Python代码"><i class="fa fa-download"></i> 本地下载</button>&nbsp;&nbsp;
		<button id="copy_to_clipboard" class="btn btn-success" href="javascript:void(0);" title="复制Python代码" data-clipboard-target="#codeDiv"><i class="fa fa-clipboard"></i> 复制到剪贴板</button>

		<div class="pull-right" style="width: 200px;">
			<div class="input-group">
				<input id="raspberry_ip" type="text" class="form-control text-center" placeholder="树莓派IP地址">
				<span class="input-group-btn">
					<button id="download_code_to_raspberry" type="button" class="btn btn-info btn-flat" title="下载到树莓派"><i class="fa fa-download"></i></button>
				</span>
			</div>
		</div>
	</div>
	<div id="blocklyDiv"></div>
	<div id="pinsDiv">
		<img src="${ctxStatic}/images/raspberry_gpio.png" width="490px" height="290px" style="margin: 4px;"/>
	</div>
	<div id="codeDiv"></div>
</div>
<% } %>
<style type="text/css">
	div.content{
		padding: 0px;
	}

	div#headDiv {
		position: absolute;
		/*background-color: #4d97ff;*/
		width: 100%;
		padding: 10px;
	}

	div#pinsDiv{
		position: absolute;
		width: 500px;
		height: 300px;
		border: 1px solid #C3CCD9;
		background-color: #ffffff;
	}

	div#codeDiv{
		position: absolute;
		width: 500px;
		border: 1px solid #C3CCD9;
		background-color: #FFFFFF;
		/*border-radius: 6px;*/
		font-size: 10px;
		padding: 6px;
		overflow: hidden;
		overflow-y: scroll;
	}

	div#blocklyDiv {
		position: absolute;
		/*border: 1px solid #C3CCD9;*/
		background-color: #FFFFFF;
		/*border-radius: 8px;*/
	}

	div#codeDiv > pre {
		border: 0px;
		overflow-x: hidden;
		/*white-space: nowrap;*/
		/*text-overflow: ellipsis;*/
	}
</style>
<link rel="stylesheet" href="${ctxStatic}/libs/base/highlight-9.18.1/styles/vs.css">

<script src="${ctxStatic}/libs/base/blockly/blockly_compressed.js"></script>
<script src="${ctxStatic}/libs/base/blockly/blocks_compressed.js"></script>
<script src="${ctxStatic}/libs/base/blockly/python_compressed.js"></script>
<script src="${ctxStatic}/libs/base/blockly/msg/js/zh-hans.js"></script>
<script src="${ctxStatic}/libs/base/highlight-9.18.1/highlight.pack.js"></script>
<script src="${ctxStatic}/libs/base/download-4.2/download-4.2.js"></script>
<script src="${ctxStatic}/libs/base/clipboard-2.0.6/clipboard-2.0.6.min.js"></script>

<script src="${ctxStatic}/libs/ext/raspberry-0.0.1/msg/messages.js"></script>
<script src="${ctxStatic}/libs/ext/time-0.0.1/msg/messages.js"></script>
<script src="${ctxStatic}/libs/ext/paho.mqtt-0.0.1/msg/messages.js"></script>
<script src="${ctxStatic}/libs/ext/demjson-0.0.1/msg/messages.js"></script>
<script src="${ctxStatic}/libs/ext/callback-0.0.1/msg/messages.js"></script>
<script src="${ctxStatic}/libs/ext/hwiot-0.0.1/msg/messages.js?t=${time}"></script>

<script src="${ctxStatic}/libs/ext/raspberry-0.0.1/blocks/pinio.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/raspberry-0.0.1/generators/pinio.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/time-0.0.1/blocks/time.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/time-0.0.1/generators/time.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/paho.mqtt-0.0.1/blocks/paho.mqtt.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/paho.mqtt-0.0.1/generators/paho.mqtt.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/demjson-0.0.1/blocks/demjson.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/demjson-0.0.1/generators/demjson.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/callback-0.0.1/blocks/callback.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/callback-0.0.1/generators/callback.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/hwiot-0.0.1/blocks/hw.iot.js?t=${time}"></script>
<script src="${ctxStatic}/libs/ext/hwiot-0.0.1/generators/hw.iot.js?t=${time}"></script>

<script type="text/javascript">
	var gap = 2;
	var workspace;
	var clipboard;

	$(function(){
		//生成模块列表区域
		workspace = Blockly.inject('blocklyDiv', {
			media: '${ctxStatic}/libs/base/blockly/media/',
			toolbox: document.getElementById('toolbox'),
			zoom: {
				controls: true,
				wheel: true,
				startScale: 1.0,
				maxScale: 3,
				minScale: 0.5,
				scaleSpeed: 1.05
			},
			trashcan: true,
			scrollBar: true
		});
		workspace.registerToolboxCategoryCallback('Category_Callbacks', function (workspace) {
			var xmlList = [];
			if((Blockly.Procedures.allProcedures(workspace)[0].length>0) && (Blockly.Blocks['callback_get'])) {
				//构造下拉列表
				var a = [];
				for (var i = 0; i < Blockly.Procedures.allProcedures(workspace)[0].length; i++) {
					var proc = Blockly.Procedures.allProcedures(workspace)[0][i];
					a.push([proc[0], proc[0]]);
				}

				//构造积木块
				for (var i = 0; i < Blockly.Procedures.allProcedures(workspace)[0].length; i++) {
					var proc = Blockly.Procedures.allProcedures(workspace)[0][i];
					var blockText = '<block type="callback_get"><field name="NAME">' + proc[0] + '</field></block>';
					var block = Blockly.Xml.textToDom(blockText);
					xmlList.push(block);
				}
			}
			return xmlList;
		});

		//尝试从XML文本加载Blockly设计项目
		var xml_text = '${blocklyProject.codeXml}';
		if(xml_text!=null && xml_text!=''){
			xml_text = xml_text.replace(/＜/g, '<');
			xml_text = xml_text.replace(/＞/g, '>');
			xml_text = xml_text.replace(/＂/g, '"');

			var xml = Blockly.Xml.textToDom(xml_text);
			Blockly.Xml.domToWorkspace(xml, workspace);
		}

		//自动调整窗口大小
		$(window).resize(function(){
			var containerWidth = $(window).width();
			var containerHeight = $(window).height();
			$('.content').css('min-height', containerHeight);

			var top = $('div#headDiv').height() + 2 * 10;

			//Blockly区域
			$('div#blocklyDiv').css('top', top + 'px');
			$('div#blocklyDiv').css('left', (2 * gap) + 'px');
			$('div#blocklyDiv').width(containerWidth - 4 * gap - $('div#pinsDiv').width() - 4 * gap);
			$('div#blocklyDiv').height(containerHeight - top - 4 * gap);

			//GPIO区域
			$('div#pinsDiv').css('top', top + 'px');
			$('div#pinsDiv').css('left', (containerWidth - 2 * gap - $('div#pinsDiv').width()) + 'px');

			top += $('div#pinsDiv').height() + 5 * gap;

			//Codes区域
			$('div#codeDiv').css('top', top + 'px');
			$('div#codeDiv').css('left', (containerWidth - 2 * gap - $('div#pinsDiv').width()) + 'px');
			$('div#codeDiv').height(containerHeight - 4 * gap - top - 12 - 2);

			Blockly.svgResize(workspace);
		}).resize();

		//生成代码按钮事件
		$('#generate_code_button').click(function () {
			var code = Blockly.Python.workspaceToCode(workspace);
			$('div#codeDiv').html('<pre><code class="python">' + code + '</code></pre>');
			// hljs.configure({useBR: true});
			hljs.highlightBlock($('div#codeDiv').children().get(0));

			js.showMessage('Python代码已经生成。', '提示', 'success');
		});
		//下载代码按钮事件
		$('#download_code').click(function () {
			download($('div#codeDiv').text(), "raspberry.py", "text/plain");
			js.showMessage('代码已经开始下载。', '提示', 'success');
		});
		//下载代码到树莓派
		$('#download_code_to_raspberry').click(function () {
			var ip = $('input#raspberry_ip').val();
			if(ip==''){
				js.showMessage('请输入树莓派IP地址。', '提示', 'warning');
				$('input#raspberry_ip').focus();
				return;
			}
			var code = Blockly.Python.workspaceToCode(workspace);
			var wsUri ="ws://" + ip + ":3081/save";
			var websocket = new WebSocket(wsUri);
			websocket.onopen = function(evt) {
				//连接打开后，发送代码
				websocket.send(code);
			};
			websocket.onmessage = function(evt) {
				var obj = eval('(' + evt.data + ')');
				if(obj.success=='true'){
					js.showMessage('代码已经成功下载到树莓派。', '提示', 'success');
				}else{
					js.showMessage('代码下载到树莓派时出现错误。' + obj.message, '提示', 'error');
				}

				//发送完成，关闭连接
				websocket.close();
			};
			// websocket.onclose = function(evt) {
			// 	onClose(evt)
			// };
			// websocket.onerror = function(evt) {
			// 	onError(evt)
			// };
		});
		//保存工作空间
		$('#save').click(function () {
			var xml = Blockly.Xml.workspaceToDom(workspace);
			var xml_text = Blockly.Xml.domToText(xml);

			$.post('./updateXml', {'id': '${blocklyProject.id}', 'codeXml': xml_text}, function (res) {
				if(res.result=='true'){
					js.showMessage('Blockly设计项目保存成功。', '提示', 'success');
				}else{
					js.showErrorMessage('Blockly设计项目保存失败。');
				}
			});
		});
		//复制程序代码
		clipboard = new ClipboardJS('#copy_to_clipboard');
		clipboard.on('success', function(e) {
			js.showMessage('已经将代码复制到剪贴板。', '提示', 'success');
		});
		clipboard.on('error', function(e) {
			js.showErrorMessage('复制出错。');
		});
	});
</script>